/**
 * Created by zl on 2017/4/18.
 */
angular.module('commonPageModule', [])
    .controller('commonPageCtrl', ['$scope','$stateParams', '$pageService','$sce', function ($scope, $stateParams, $pageService, $sce) {
        console.log('params: '+ JSON.stringify($stateParams));
        $scope.menuKeyCode = $stateParams.menuKeyCode;
        $scope.subMenuId = $stateParams.subMenuId;

        //填写捐赠相关的信息
        $scope.donate = {
            customMoney:0,
            totalFee: 50,
            payType: 'WX',
            publicFlag: 1,
            userType: 1,
            moneyIndex : 1
        };

        $scope.helpMessage = {};

        $scope.showProjectDetail = true;

        //面包屑导航
        $scope.locationStr = '';

        $scope.selectedContent = $scope.contentId;

        $scope.currentPage = 1;
        $scope.numberPerPage = 5;
        if(!$scope.menuKeyCode || !$scope.subMenuId){
            console.log('未知页面!');
            return ;
        }

        $scope.subMenus = $pageService.getSubMenus(null, $scope.menuKeyCode);
        $scope.selectedMenu = $pageService.getSubMenu($scope.subMenuId);

        //子菜单时候支持多条内容
        $scope.itemIsMulti = $scope.selectedMenu.subMenuMulti || 'N';
        //是否支持评论
        $scope.isSupportComment = $scope.selectedMenu.subMenuSupportComment|| 'N';
        $scope.isSupportDonate = $scope.selectedMenu.subMenuSupportDonate|| 'N';

        //相关方法初始化
        $scope.querySingleContentData = function () {
            //查询内容
            $pageService.getContent($scope.selectedMenu.subMenuId, $scope.selectedContent).then(function(results){
                if(results && results.code == 0){
                    $scope.contentData = results.data || {};
                    $scope.contentData.content = $sce.trustAsHtml($scope.contentData.content);

                    $scope.locationStr = $sce.trustAsHtml('您当前的位置：'+$scope.selectedMenu.menuName+'>>'+ $scope.selectedMenu.subMenuName+'>><span>'+$scope.contentData.name+'</span>');

                    console.log('contentData '+ JSON.stringify($scope.contentData));
                }
                else{
                    console.log('查询数据失败');
                }

            });
        }

        $scope.getSingleContentByMenu = function () {
            //查询内容
            $pageService.getFirstContentByMenu($scope.selectedMenu.subMenuId).then(function(results){
                if(results && results.code == 0){
                    $scope.contentData = results.data || {};
                    $scope.contentData.content = $sce.trustAsHtml($scope.contentData.content);

                    $scope.locationStr = $sce.trustAsHtml('您当前的位置：'+$scope.selectedMenu.menuName+'>>'+ $scope.selectedMenu.subMenuName+'>><span>'+$scope.contentData.name+'</span>');

                    console.log('contentData '+ JSON.stringify($scope.contentData));
                }
                else{
                    console.log('查询数据失败');
                }

            });
        }

        $scope.queryCurrentPageContentList = function () {
            //更新面包屑信息
            $scope.locationStr = $sce.trustAsHtml('您当前的位置：'+$scope.selectedMenu.menuName+'>><span>'+$scope.selectedMenu.subMenuName+'</span>');

            //查询子菜单内容
            $pageService.getContentList($scope.selectedMenu.subMenuId, ($scope.currentPage-1)*$scope.numberPerPage, $scope.numberPerPage).then(function(results){
                if(results && results.code == 0){
                    $scope.contentList = results.data;
                    console.log('contentList '+ JSON.stringify($scope.contentList));
                }
                else{
                    console.log('查询数据失败');
                }
            });
        }

        $scope.selectSubMenu = function (subMenuId) {

            if($scope.selectedMenu.subMenuId == subMenuId){
                return;
            }

            $scope.selectedMenu = $pageService.getSubMenu(subMenuId);
            $scope.currentPage = 1;
            $scope.selectedContent = "";

            //子菜单时候支持多条内容
            $scope.itemIsMulti = $scope.selectedMenu.subMenuMulti || 'N';
            //是否支持评论
            $scope.isSupportComment = $scope.selectedMenu.subMenuSupportComment|| 'N';
            $scope.isSupportDonate = $scope.selectedMenu.subMenuSupportDonate|| 'N';

            //若只显示内容,无内容列表
            if($scope.itemIsMulti === 'N'){
                $scope.getSingleContentByMenu();
            }
            else{
                $scope.queryCurrentPageContentList();
            }
        }

        $scope.projectMenuBtnClick = function () {
            $scope.showProjectDetail = true;
        }
        $scope.donateMenuBtnClick = function () {
            $scope.showProjectDetail = false;
        }

        $scope.toPreviousPage = function () {
            if($scope.currentPage <= 1){
                return ;
            }
            $scope.currentPage --;
            $scope.selectedContent = '';
            $scope.queryCurrentPageContentList();
        }
        $scope.toNextPage = function () {
            if($scope.contentList.length < $scope.numberPerPage){
                return;
            }
            $scope.currentPage ++;
            $scope.selectedContent = '';
            $scope.queryCurrentPageContentList();
        }

        $scope.selectSingleContent = function (contentId) {
            $scope.selectedContent = contentId;
            $scope.querySingleContentData()
        }

        $scope.sendMessage = function (contentId) {
            $scope.helpMessage.contentId = contentId;

            if(!verifyPhoneNum($scope.helpMessage.contact)){
                $scope.helpMessage.errorMessage = "请输入正确的手机号";
                return ;
            }

            $pageService.sendMessage($scope.helpMessage).then(function (result) {
                if (result && result.message) {
                    $scope.helpMessage.errorMessage = result.message
                }
            })
        }


        if($scope.selectedContent){
            $scope.querySingleContentData();
        }
        else if($scope.itemIsMulti === 'N'){
            $scope.getSingleContentByMenu();
        }
        else{
            $scope.queryCurrentPageContentList();
        }

        $scope.selectMoney = function (moneyIndex) {
            $scope.donate.moneyIndex = moneyIndex;
        };

        $scope.selectPayType = function (payType) {
            $scope.donate.payType = payType;
        };

        $scope.toDonate = function (event) {
            $scope.donate.publicFlag = $scope.donate.publicFlag || 0;

            switch ($scope.donate.moneyIndex) {
                case  1:
                    $scope.donate.totalFee = 50;
                    break;
                case  2:
                    $scope.donate.totalFee = 100;
                    break;
                case  3:
                    $scope.donate.totalFee = 200;
                    break;
                case  4:
                    $scope.donate.totalFee = $scope.donate.customMoney;
                    break;
                default:
                    $scope.donate.totalFee = 50;
                    break;
            }

            if(!verifyMoney($scope.donate.totalFee)  || parseFloat($scope.donate.totalFee) <= 0){
                $scope.donate.errorMessage = '请填写正确的捐款金额';
                event.preventDefault();
                return;
            }

            if($scope.donate.payType !== 'WX' && $scope.donate.payType != 'ALi'){
                $scope.donate.errorMessage = '请选择支付类型';
                event.preventDefault();
                return;
            }

            //验证用户姓名
            if(!$scope.donate.userName){
                $scope.donate.errorMessage = '请填写捐款人姓名';
                event.preventDefault();
                return;
            }

            //验证用户公司姓名格式
            if($scope.donate.userType == 2 && !$scope.donate.userCompany){
                $scope.donate.errorMessage = '请填写捐款人公司名';
                event.preventDefault();
                return;
            }

            // 验证用户手机号
            if(!verifyPhoneNum($scope.donate.userPhoneNumber)){
                $scope.donate.errorMessage = '请填写正确的手机号码';
                event.preventDefault();
                return;
            }
            //验证邮箱格式
            if(!verifyEmail($scope.donate.userEmail)){
                $scope.donate.errorMessage  = '请填写正确的电子邮箱';
                event.preventDefault();
                return;
            }
            //debugger;
            //阻止提交
            //  event.preventDefault();
        };

}])
    .factory('$pageService', ['$http', function ($http) {
        return {
            getSubMenus: function (menuId, menuKeyCode) {
                window.LOCAL_STORE.context.session = window.LOCAL_STORE.context.session || {};
                window.LOCAL_STORE.context.session.globalMenus = window.LOCAL_STORE.context.session.globalMenus || [];
                var subMenus = [];
                for(var index = 0; index < window.LOCAL_STORE.context.session.globalMenus.length; index ++ ){

                    if(menuId && window.LOCAL_STORE.context.session.globalMenus[index].menuId === menuId){
                        subMenus.push(window.LOCAL_STORE.context.session.globalMenus[index]);
                    }
                    else if(menuKeyCode && window.LOCAL_STORE.context.session.globalMenus[index].menuKeyCode === menuKeyCode){
                        subMenus.push(window.LOCAL_STORE.context.session.globalMenus[index]);
                    }
                }
                return subMenus;
            },

            getSubMenu: function (subMenuId) {
                var subMenu = {};
                window.LOCAL_STORE.context.session = window.LOCAL_STORE.context.session || {};
                window.LOCAL_STORE.context.session.globalMenus = window.LOCAL_STORE.context.session.globalMenus || [];
                for(var index = 0; index < window.LOCAL_STORE.context.session.globalMenus.length; index ++ ){
                    if(window.LOCAL_STORE.context.session.globalMenus[index].subMenuId === subMenuId){
                        subMenu = window.LOCAL_STORE.context.session.globalMenus[index];
                        break;
                    }
                }
                return subMenu;
            },

            getContent: function (subMenuId, contentId) {
                return $http({
                    method:'GET',
                    url:'/articles/'+subMenuId+'/'+contentId
                }).then(function (result) {
                    return result.data;
                });
            },
            getFirstContentByMenu: function (subMenuId) {
                return $http({
                    method: 'GET',
                    url: '/articles/' + subMenuId,
                    params: {
                        singleData: 'Y'
                    }
                }).then(function (result) {
                    return result.data;
                });
            },
            getContentList: function (subMenuId, skip, limit) {
                return $http({
                    method: 'GET',
                    url: '/articles/' + subMenuId,
                    params: {skip: skip, limit: limit}
                }).then(function (result) {
                    return result.data;
                });
            },
            sendMessage: function (messageData) {
                return $http({
                    method: 'POST',
                    url: '/messages/',
                    data: messageData
                }).then(function (result) {
                    return result.data;
                });
            }

        }

}]);